from django.shortcuts import render, redirect, reverse
from .forms import UserRegisterForm, UserLoginForm, UserForgetForm, UserResetForm, UserChangeImageForm, \
    UserChangeInfoForm, UserChangeEmailForm, UserResetEmailForm
from .models import UserProFile, EmailVerifyCode, BannerInfo
from operations.models import UserLove, UserMessage
from orgs.models import OrgInfo, TeacherInfo
from courses.models import CourseInfo
from django.db.models import Q
from django.contrib.auth import authenticate, logout, login
from django.http import HttpResponse, JsonResponse
from tools.send_mail_tool import send_mail_code
from tools.decorators import login_decorator
from datetime import datetime
from django.views.generic import View


# 将view方法改成类
# fbv:基于函数的视图  cbv:基于类的视图  Mixin:写好的一些基础类  在大项目中cbv优于fbv
class IndexView(View):
    def get(self, request):
        all_banners = BannerInfo.objects.all().order_by('-add_time')[:5]
        all_course = CourseInfo.objects.filter(is_banner=False)[:6]
        course_banners = CourseInfo.objects.filter(is_banner=True)[:3]
        all_org = OrgInfo.objects.all()
        return render(request, 'index.html', {
            'all_banners': all_banners,
            'course_banners': course_banners,
            'all_course': all_course,
            'all_org': all_org
        })


# def index(request):
#     all_banners = BannerInfo.objects.all().order_by('-add_time')[:5]
#     all_course = CourseInfo.objects.filter(is_banner=False)[:6]
#     course_banners = CourseInfo.objects.filter(is_banner=True)[:3]
#     all_org = OrgInfo.objects.all()
#     return render(request, 'index.html', {
#         'all_banners': all_banners,
#         'course_banners': course_banners,
#         'all_course': all_course,
#         'all_org': all_org
#     })


def user_register(request):
    if request.method == 'GET':
        # 这里实例化froms类,目的不是为了验证,而是为了使用验证码
        user_register_form = UserRegisterForm()
        return render(request, 'users/register.html', {
            'user_register_form': user_register_form
        })
    elif request.method == 'POST':
        user_register_form = UserRegisterForm(request.POST)
        if user_register_form.is_valid():
            email = user_register_form.cleaned_data['email']
            password = user_register_form.cleaned_data['password']

            user_list = UserProFile.objects.filter(Q(username=email) | Q(email=email))
            if user_list:
                return render(request, 'users/register.html', {
                    'msg': '用户已经存在'
                })
            else:
                user = UserProFile()
                user.username = email
                user.set_password(password)
                user.email = email
                user.save()
                send_mail_code(email, 1)
                return HttpResponse('请尽快前往您的邮箱激活,否则无法登入')
        else:
            return render(request, 'users/register.html', {
                'user_register_form': user_register_form
            })


def user_login(request):
    if request.method == 'GET':
        return render(request, 'users/login.html')
    elif request.method == 'POST':
        user_login_form = UserLoginForm(request.POST)
        if user_login_form.is_valid():
            email = user_login_form.cleaned_data['email']
            password = user_login_form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user:
                if user.is_start:
                    login(request, user)
                    # 一旦登入成功,写入用户消息
                    UserMessage.objects.create(
                        message_man=user.id,
                        message_content='欢迎登入'
                    )

                    url = request.COOKIES.get('url', '/')
                    ret = redirect(url)
                    ret.delete_cookie('url')
                    return ret
                else:
                    return HttpResponse('请去您的邮箱激活,否则无法登入')
            else:
                return render(request, 'users/login.html', {
                    'msg': '邮箱或者密码有误'
                })
        else:
            return render(request, 'users/login.html', {
                'user_login_form': user_login_form
            })


def user_logout(request):
    logout(request)
    return redirect(reverse('index'))


def user_active(request, code):
    if code:
        email_ver_list = EmailVerifyCode.objects.filter(code=code)
        if email_ver_list:
            email_ver = email_ver_list[0]
            user_list = UserProFile.objects.filter(username=email_ver.email)
            if user_list:
                user = user_list[0]
                user.is_start = True
                user.save()
                return redirect(reverse('users:user_login'))
            else:
                pass
        else:
            pass
    else:
        pass


def user_forget(request):
    if request.method == 'GET':
        user_forget_form = UserForgetForm()
        return render(request, 'users/forgetpwd.html', locals())
    elif request.method == 'POST':
        user_forget_form = UserForgetForm(request.POST)
        if user_forget_form.is_valid():
            email = user_forget_form.cleaned_data['email']
            user_list = UserProFile.objects.filter(username=email)
            if user_list:
                send_mail_code(email, 2)
                return HttpResponse('请尽快去您的邮箱去重置密码')
            else:
                return render(request, 'users/forgetpwd.html', {
                    'msg': '用户不存在'
                })
        else:
            return render(request, 'users/forgetpwd.html', locals())


def user_reset(request, code):
    if code:
        if request.method == 'GET':
            return render(request, 'users/password_reset.html', {
                'code': code
            })
        elif request.method == 'POST':
            user_reset_form = UserResetForm(request.POST)
            if user_reset_form.is_valid():
                password = user_reset_form.cleaned_data['password']
                password1 = user_reset_form.cleaned_data['password1']
                if password == password1:
                    email_ver_list = EmailVerifyCode.objects.filter(code=code)
                    if email_ver_list:
                        email = email_ver_list[0].email
                        user_list = UserProFile.objects.filter(email=email)
                        if user_list:
                            user = user_list[0]
                            user.set_password(password)
                            user.save()
                            return redirect(reverse('users:user_login'))
                        else:
                            pass
                    else:
                        pass
                else:
                    return render(request, 'users/password_reset.html', {
                        'msg': '两次密码不一致',
                        'code': code
                    })
            else:
                return render(request, 'users/password_reset.html', {
                    'user_reset_form': user_reset_form,
                    'code': code
                })


def user_info(request):
    return render(request, 'users/usercenter-info.html')


# 修改头像
def user_change_image(request):
    # instance 指明实例是什么,做修改的时候,我们需要知道是给哪个对象实例进行修改
    # 如果不指明,那么就会被当做创建对象去执行,而我们只有一个图片,就一定会报错
    user_change_image_form = UserChangeImageForm(request.POST, request.FILES, instance=request.user)
    if user_change_image_form.is_valid():
        user_change_image_form.save(commit=True)
        return JsonResponse({'status': 'ok'})
    else:
        return JsonResponse({'status': 'fail'})


def user_change_info(request):
    user_change_info_form = UserChangeInfoForm(request.POST, instance=request.user)

    if user_change_info_form.is_valid():
        user_change_info_form.save(commit=True)
        return JsonResponse({'status': 'ok', 'msg': '修改成功'})
    else:
        return JsonResponse({'status': 'fail', 'msg': '修改失败'})


def user_change_email(request):
    user_change_email_form = UserChangeEmailForm(request.POST)
    if user_change_email_form.is_valid():
        email = user_change_email_form.cleaned_data['email']
        user_list = UserProFile.objects.filter(Q(email=email) | Q(username=email))
        if user_list:
            return JsonResponse({'status': 'fail', 'msg': '邮箱已经被绑定'})
        else:
            # 查询是否发送过验证码
            email_ver_list = EmailVerifyCode.objects.filter(email=email, send_type=3)
            if email_ver_list:
                # 如果发送了,拿到最近时间发送的验证码
                email_ver = email_ver_list.order_by('-add_time')[0]
                if (datetime.now() - email_ver.add_time).seconds > 60:
                    send_mail_code(email, 3)
                    # 重新发送验证码以后,删除旧的验证码
                    email_ver.delete()
                    return JsonResponse({'status': 'ok', 'msg': '请尽快去邮箱当中获取验证码'})
                else:
                    return JsonResponse({'status': 'fail', 'msg': '请不要重复发送验证码,1分钟后重试'})
            else:
                send_mail_code(email, 3)
                return JsonResponse({'status': 'ok', 'msg': '请尽快去邮箱当中获取验证码'})
    else:
        return JsonResponse({'status': 'fail', 'msg': '邮箱格式不正确'})


def user_reset_email(request):
    user_reset_email_form = UserResetEmailForm(request.POST)
    if user_reset_email_form.is_valid():
        email = user_reset_email_form.cleaned_data['email']
        code = user_reset_email_form.cleaned_data['code']
        email_ver_list = EmailVerifyCode.objects.filter(email=email, code=code)
        if email_ver_list:
            email_var = email_ver_list[0]
            if (datetime.now() - email_var.add_time).seconds < 60:
                request.user.username = email
                request.user.email = email
                request.user.save()
                return JsonResponse({'status': 'ok', 'msg': '邮箱修改成功'})
            else:
                return JsonResponse({'status': 'fail', 'msg': '验证码失效,请重新发送验证码'})
        else:
            return JsonResponse({'status': 'fail', 'msg': '邮箱或者验证码输入错误'})
    else:
        return JsonResponse({'status': 'fail', 'msg': '邮箱格式不正确'})


@login_decorator
def user_course(request):
    user_course_list = request.user.usercourse_set.all()
    course_list = [user_course.study_course for user_course in user_course_list]
    return render(request, 'users/usercenter-mycourse.html', {
        'course_list': course_list,
    })


@login_decorator
def user_love_org(request):
    # love_org_list = request.user.userlove_set.all().filter(love_type=1)
    love_org_list = UserLove.objects.filter(love_man=request.user, love_type=1, love_status=True)
    org_ids = [love_org.love_id for love_org in love_org_list]
    org_list = OrgInfo.objects.filter(id__in=org_ids)
    return render(request, 'users/usercenter-fav-org.html', {
        'org_list': org_list,
    })


@login_decorator
def user_love_teacher(request):
    love_teacher_list = UserLove.objects.filter(love_man=request.user, love_type=3, love_status=True)
    teacher_ids = [love_teacher.love_id for love_teacher in love_teacher_list]
    teacher_list = TeacherInfo.objects.filter(id__in=teacher_ids)
    return render(request, 'users/usercenter-fav-teacher.html', {
        'teacher_list': teacher_list
    })


@login_decorator
def user_love_course(request):
    love_course_list = UserLove.objects.filter(love_man=request.user, love_type=2, love_status=True)
    course_ids = [love_course.love_id for love_course in love_course_list]
    course_list = CourseInfo.objects.filter(id__in=course_ids)
    return render(request, 'users/usercenter-fav-course.html', {
        'course_list': course_list
    })


def user_message(request):
    msg_list = UserMessage.objects.filter(message_man=request.user.id)
    return render(request, 'users/usercenter-message.html', {
        'msg_list': msg_list
    })


def user_delete_message(request):
    msg_id = request.GET.get('msg_id', '')
    if msg_id:
        msg = UserMessage.objects.filter(id=int(msg_id))[0]
        msg.message_status = True
        msg.save()
        return JsonResponse({'status': 'ok', 'msg': '已读'})
    else:
        return JsonResponse({'status': 'fail', 'msg': '读取失败'})


def handler_404(request, *args, **kwargs):
    return render(request, 'handler404.html')


def handler_500(request, *args, **kwargs):
    return render(request, 'handler500.html')
